package com.hzh.cusviewdemo.Activity;

import static com.hzh.cusviewdemo.Music.PlayerManagerReceiver.status;

import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.cbman.roundimageview.RoundImageView;
import com.hzh.cusviewdemo.Adapter.SearchResultAdapter;
import com.hzh.cusviewdemo.Base.BaseActivity;
import com.hzh.cusviewdemo.Bean.MusicInfoData;
import com.hzh.cusviewdemo.Bean.MusicSearchData;
import com.hzh.cusviewdemo.Bean.MyMusicData;
import com.hzh.cusviewdemo.Bean.MySongMenu;
import com.hzh.cusviewdemo.Bean.SearchRecord;
import com.hzh.cusviewdemo.Fragment.PlayMusicFragment;
import com.hzh.cusviewdemo.Music.Constant;
import com.hzh.cusviewdemo.Music.MusicPlayService;
import com.hzh.cusviewdemo.Music.MyMusicUtil;
import com.hzh.cusviewdemo.Presenter.MusicPresenter;
import com.hzh.cusviewdemo.R;
import com.hzh.cusviewdemo.Ui.ClearEditText;
import com.hzh.cusviewdemo.Ui.CustomSeekBar;
import com.hzh.cusviewdemo.Ui.TagLayout.FlowLayout;
import com.hzh.cusviewdemo.Ui.TagLayout.TagAdapter;
import com.hzh.cusviewdemo.Ui.TagLayout.TagFlowLayout;
import com.hzh.cusviewdemo.Ui.classicFoot.footer.ClassicsFooter;
import com.hzh.cusviewdemo.Util.Config;
import com.hzh.cusviewdemo.Util.DialogUtils;
import com.hzh.cusviewdemo.Util.SugarUtils;
import com.hzh.cusviewdemo.Util.ThreadPoolManager;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.orm.SugarRecord;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseActivity implements View.OnClickListener, MusicPresenter {

    private ClearEditText as_content;
    private ImageView as_back;
    private TextView as_to_search;
    private NestedScrollView as_nested_history;
    private ImageView as_delete_history;
    private TagFlowLayout as_search_flow;
    private TextView as_no_history;
    private SmartRefreshLayout as_smart;
    private RecyclerView as_list_result;

    private ImageView as_play;
    private TextView as_song_info;
    private TextView as_song_progress;
    private ProgressBar as_load_time;
    private CustomSeekBar as_seekbar;
    private RoundImageView as_cover_pic;
    private boolean isPlayFragmentShow;
    private PlayMusicFragment mPlayFragment;
    private boolean isPlayMusic = false;

    private TagAdapter<String> mSearchRecordAdapter;

    // 分页列表控件
    private SearchResultAdapter searchResultAdapter; // 搜索结果的适配器
    private List<MusicSearchData> dataList = new ArrayList<>();  // 搜索结果
    private int pageNum = 1; // 初始load页

    @Override
    public int getLayout() {
        return R.layout.activity_search;
    }

    @Override
    public void initView() {
        register();

        as_back = findViewById(R.id.as_back);
        as_content = findViewById(R.id.as_content);
        as_to_search = findViewById(R.id.as_to_search);
        as_nested_history = findViewById(R.id.as_nested_history);
        as_delete_history = findViewById(R.id.as_delete_history);
        as_search_flow = findViewById(R.id.as_search_flow);
        as_no_history = findViewById(R.id.as_no_history);
        as_smart = findViewById(R.id.as_smart);
        as_list_result = findViewById(R.id.as_list_result);

        as_play = findViewById(R.id.as_play);
        as_song_info = findViewById(R.id.as_song_info);
        as_song_progress = findViewById(R.id.as_song_progress);
        as_seekbar = findViewById(R.id.as_seekbar);
        as_load_time = findViewById(R.id.as_load_time);
        as_cover_pic = findViewById(R.id.as_cover_pic);

        isPlayMusic = getIntent().getBooleanExtra("TAG_IS_PLAYING", false);

        as_content.setOnClearListener(() -> {
            // 清空内容，重置
            as_nested_history.setVisibility(View.VISIBLE);
            as_smart.setVisibility(View.GONE);
            dataList.clear();
            pageNum = 1;
            searchResultAdapter.resetAdapter();
        });
        as_content.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String content = as_content.getText().toString().trim();
                if (ObjectUtils.isEmpty(content)) {
                    DialogUtils.showErrorToast("搜索内容不得为空~");
                } else {
                    ToSearchMusic(content);
                }
                return false;
            }
            return false;
        });

        // 播放监听
        as_play.setOnClickListener(v -> {
            String musicUrl = MyMusicUtil.getStringShared(Constant.KEY_PATH);
            if (musicUrl.equals("")) {
                Log.e(Config.TAG, "musicUrl is null");
                Intent intent = new Intent();
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_STOP);
                sendBroadcast(intent);
                Toast.makeText(SearchActivity.this, "歌曲不存在", Toast.LENGTH_SHORT).show();
                return;
            }
            //如果当前媒体在播放音乐状态，则图片显示暂停图片，按下播放键，则发送暂停媒体命令，图片显示播放图片。以此类推。
            if (status == Constant.STATUS_PAUSE) {
                MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(MyMusicUtil.getStringShared(Constant.KEY_ID));
                Log.e(Config.TAG, "status == Constant.STATUS_PAUSE\nLAST PATH：" + musicDataByRid.getUrl());
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                intent.putExtra(Constant.KEY_PATH, musicDataByRid.getUrl());
                intent.putExtra(Constant.KEY_ID, MyMusicUtil.getStringShared(Constant.KEY_ID));
                intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
                sendBroadcast(intent);
            } else if (status == Constant.STATUS_PLAY) {
                Log.e(Config.TAG, "status == Constant.STATUS_PLAY");
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PAUSE);
                sendBroadcast(intent);
            } else {
                Log.e(Config.TAG, "status == " + status);
                //为停止状态时发送播放命令，并发送将要播放歌曲的路径
                setMusicName();
                Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                intent.putExtra(Constant.KEY_PATH, MyMusicUtil.getStringShared(Constant.KEY_PATH));
                sendBroadcast(intent);
            }
        });

        as_seekbar.setProgressListener(progress -> {
            Log.e(Config.TAG, "MA:进度改变");
            // 拖动进度
            Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
            intent.putExtra(Constant.COMMAND, Constant.COMMAND_PROGRESS);
            intent.putExtra(Constant.KEY_CURRENT, progress * 1000);
            sendBroadcast(intent);
        });

        as_cover_pic.setOnClickListener(v -> showPlayingFragment());


        as_smart.setEnableRefresh(false);
        as_smart.setRefreshFooter(new ClassicsFooter(this));
        as_smart.setOnLoadMoreListener(refreshLayout -> {
            if (searchResultAdapter != null) {
                searchMusicPage(as_content.getText().toString().trim(), String.valueOf(pageNum), "20", new OnSearchMusicListener() {
                    @Override
                    public void onGetMusicSuccess(List<MusicSearchData> result) {
                        pageNum++;
                        searchResultAdapter.addAll(result);
                        searchResultAdapter.loadMore();
                    }

                    @Override
                    public void onGetMusicFail(String msg) {
                        DialogUtils.showErrorToast("没有更多数据了~");
                    }
                });
                as_smart.finishLoadMore(500);//传入false表示加载失败
            } else {
                as_smart.finishLoadMore();
            }
        });

        as_back.setOnClickListener(this);
        as_to_search.setOnClickListener(this);
        as_delete_history.setOnClickListener(this);

        WaitDialog.show("...");
        showPlayingFragment();
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            hidePlayingFragment();
            WaitDialog.dismiss();
        },500);

    }

    private void showPlayingFragment() {
        if (isPlayFragmentShow) {
            return;
        }
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.fragment_slide_up, 0);
        if (mPlayFragment == null) {
            mPlayFragment = new PlayMusicFragment(isPlayMusic);
            ft.replace(android.R.id.content, mPlayFragment);
        } else {
            ft.show(mPlayFragment);
        }
        ft.commitAllowingStateLoss();
        isPlayFragmentShow = true;
    }

    private void setMusicName() {
        String musicPic = MyMusicUtil.getStringShared(Constant.KEY_PIC);
        String musicName = MyMusicUtil.getStringShared(Constant.KEY_NAME);
        String musicSonger = MyMusicUtil.getStringShared(Constant.KEY_SONGER);
        if (musicName.equals("") && musicSonger.equals("")) {
            as_song_info.setText("听歌神器 - For QJL");
        } else {
            as_song_info.setText(musicName + " - " + musicSonger);
            as_load_time.setVisibility(View.VISIBLE);
        }
        as_song_progress.setText("00:00 / 00:00");
        if (musicPic != null && !musicPic.isEmpty()) {
            Glide.with(SearchActivity.this).load(musicPic).placeholder(R.drawable.ic_logo).error(R.drawable.ic_logo).into(as_cover_pic);
        }
    }

    public static final String ACTION_UPDATE_UI_MUSIC = "com.hzh.cusviewdemo.Activity.MusicActivity:action_update_ui_broad_cast";
    private SearchReceiver mReceiver;

    private void register() {
        // 执行
        mReceiver = new SearchReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_UPDATE_UI_MUSIC);
        registerReceiver(mReceiver, intentFilter);
    }

    private void unRegister() {
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    class SearchReceiver extends BroadcastReceiver {
        int status;
        int duration;
        int current;
        String currentSentence;
        String coverPic; // 封面图片

        @Override
        public void onReceive(Context context, Intent intent) {
            status = intent.getIntExtra(Constant.STATUS, 0);
            current = intent.getIntExtra(Constant.KEY_CURRENT, 0);
            duration = intent.getIntExtra(Constant.KEY_DURATION, 100);
            currentSentence = intent.getStringExtra(Constant.KEY_CURRENT_SENTENCE);
            coverPic = intent.getStringExtra(Constant.KEY_PIC);
            switch (status) {
                case Constant.STATUS_STOP:
                    showPlayStatus(false);
                    as_seekbar.progress(0);
                    break;
                case Constant.STATUS_PLAY:
                    showPlayStatus(true);
                    break;
                case Constant.STATUS_PAUSE:
                    showPlayStatus(false);
                    break;
                case Constant.STATUS_RUN:
                    showPlayStatus(true);
                    as_song_progress.setText(com.hzh.cusviewdemo.Util.TimeUtils.stampToDateS(current, "mm:ss") + " / " + com.hzh.cusviewdemo.Util.TimeUtils.stampToDateS(duration, "mm:ss"));
                    as_seekbar.setMaxProgress(duration / 1000);
                    as_seekbar.progress(current / 1000);
                    as_song_info.setText(currentSentence);
                    // Log.e(Config.TAG, "歌曲时长：" + duration + "--当前进度：" + current);
                    break;
                case Constant.STATUS_LOAD_OK:
                    // 加载封面图片
                    Glide.with(SearchActivity.this).load(coverPic).placeholder(R.drawable.ic_logo).error(R.drawable.ic_logo).into(as_cover_pic);
                    MyMusicUtil.setShared(Constant.KEY_LRC_LIST, intent.getStringExtra(Constant.KEY_LRC_LIST));
                    as_load_time.setVisibility(View.GONE);
                    break;
                case Constant.STATUS_REFRESH_LIKE_FROM_PLAY_PAGE:
                    // 在播放页面点击喜欢 刷新列表
                    if (searchResultAdapter != null) {
                        searchResultAdapter.notifyDataSetChanged();
                    }
                    break;
                default:
                    break;
            }

        }

    }

    public void showPlayStatus(boolean isPlay) {
        runOnUiThread(() -> as_play.setImageResource(isPlay ? R.drawable.ic_play_song : R.drawable.ic_stop_song));
    }

    @Override
    public void initData() {
        // 加载历史记录
        initHistoryList();

        searchResultAdapter = new SearchResultAdapter(this, dataList);
        searchResultAdapter.setOnListenMusicListener(new SearchResultAdapter.OnListenMusicListener() {
            @Override
            public void onListenMusic(MusicSearchData musicSearchData, int pos, boolean isLike) {
                listenMusic(SearchActivity.this, musicSearchData.getId(), new MusicPresenter.OnListenMusicListener() {
                    @Override
                    public void onListenSuccess(MusicInfoData data) {
                        MyMusicUtil.setShared(Constant.KEY_NAME, data.getSongname());
                        MyMusicUtil.setShared(Constant.KEY_SONGER, data.getSonger());
                        MyMusicUtil.setShared(Constant.KEY_PIC, data.getSongpic());
                        String songTitle = data.getSongname() + " - " + data.getSonger();

                        // 获取到musicUrl
                        // 先暂停
                        Intent stopIntent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                        stopIntent.putExtra(Constant.COMMAND, Constant.COMMAND_STOP);
                        sendBroadcast(stopIntent);

                        MyMusicUtil.setShared(Constant.KEY_PATH, data.getSongurl());
                        MyMusicUtil.setShared(Constant.KEY_ID, String.valueOf(data.getSid()));
                        MyMusicUtil.setShared(Constant.KEY_TITLE, songTitle);

                        Log.e(Config.TAG, "MA:保存本地播放列表：" + data.getSongname() + " - SID -> " + data.getSid());

                        MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(data.getSid());
                        MyMusicData nextData = new MyMusicData();
                        if (musicDataByRid == null) {
                            // 添加到本地播放列表
                            nextData.setRid(data.getSid());
                            nextData.setSid(data.getSid());
                            nextData.setName(data.getSongname());
                            nextData.setSonger(data.getSonger());
                            nextData.setTitle(songTitle);
                            nextData.setPic(data.getSongpic());
                            nextData.setUrl(data.getSongotherurl());
                            nextData.setLrc(data.getSonglrc());
                            nextData.setType("0"); // 顺序播放
                            nextData.setMenu(!isLike ? "全部歌曲" : "我喜欢的音乐");
                            nextData.setCreateTime(TimeUtils.getNowString());
                            SugarUtils.addMusicData(nextData);

                            // 更新歌单
                            MySongMenu songMenu = SugarUtils.getSongMenuByName(!isLike ? "全部歌曲" : "我喜欢的音乐");
                            if (songMenu != null) {
                                songMenu.setNum(songMenu.getNum() + 1);
                                songMenu.setPic(data.getSongpic());
                                songMenu.setUpdateTime(TimeUtils.getNowString());
                                songMenu.save();
                            }
                        } else {
                            musicDataByRid.setUrl(data.getSongotherurl());
                            musicDataByRid.setLrc(data.getSonglrc());
                            musicDataByRid.save();
                        }

                        // 搜索的歌曲默认设置当前歌单为全部歌曲
                        MyMusicUtil.setShared(Constant.KEY_NOW_PLAY_MENU, !isLike ? "全部歌曲" : "我喜欢的音乐");

                        // 通知MusicActivity处理STATUS_CLICK_SEARCH_RESULT_PLAY状态广播
                        Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);
                        musicIntent.putExtra(Constant.STATUS, Constant.STATUS_CLICK_SEARCH_RESULT_PLAY);
                        sendBroadcast(musicIntent);

                        // 通知播放音乐
                        Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                        intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                        intent.putExtra(Constant.KEY_PATH, data.getSongotherurl());
                        intent.putExtra(Constant.KEY_ID, musicDataByRid == null ? nextData.getSid() : musicDataByRid.getSid());
                        intent.putExtra(Constant.KEY_TITLE, songTitle);
                        sendBroadcast(intent);

                        searchResultAdapter.setPlaying(pos);

                        Intent updateUiIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);
                        updateUiIntent.putExtra(Constant.STATUS, Constant.STATUS_REFRESH_LIKE_FROM_SEARCH_LIST);
                        sendBroadcast(updateUiIntent);
                    }

                    @Override
                    public void onListenFail(String msg) {
                        ToastUtils.showShort(msg);

                        Intent updateUiIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);
                        updateUiIntent.putExtra(Constant.STATUS, Constant.STATUS_REFRESH_LIKE_FROM_SEARCH_LIST);
                        sendBroadcast(updateUiIntent);
                    }
                });
            }
        });
        as_list_result.setLayoutManager(new LinearLayoutManager(this));
        as_list_result.setAdapter(searchResultAdapter);
    }

    /**
     * 加载历史记录
     */
    private void initHistoryList() {
        ThreadPoolManager.getInstance().execute(() -> {
            List<SearchRecord> allSearchRecord = SugarUtils.getAllSearchRecord();
            runOnUiThread(() -> {
                if (allSearchRecord.size() > 0) {
                    as_search_flow.setVisibility(View.VISIBLE);
                    as_no_history.setVisibility(View.GONE);
                    as_delete_history.setVisibility(View.VISIBLE);
                    // 显示列表
                    showSearchHistory(allSearchRecord);
                } else {
                    as_search_flow.setVisibility(View.GONE);
                    as_no_history.setVisibility(View.VISIBLE);
                    as_delete_history.setVisibility(View.GONE);
                }
            });
        });
    }

    /**
     * 显示历史记录列表
     *
     * @param allSearchRecord
     */
    private void showSearchHistory(List<SearchRecord> allSearchRecord) {
        List<String> searchList = new ArrayList<>();
        for (SearchRecord record : allSearchRecord) {
            if (record == null) {
                continue;
            }
            searchList.add(record.getContent());
        }
        mSearchRecordAdapter = new TagAdapter<String>(searchList) {
            @Override
            public View getView(FlowLayout parent, int position, String record) {
                TextView tv = (TextView) LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_search_history, as_search_flow, false);
                //为标签设置对应的内容
                tv.setText(record);
                return tv;
            }
        };
        as_search_flow.setAdapter(mSearchRecordAdapter);
        as_search_flow.setOnTagClickListener((view, position, parent) -> {
            as_content.setText(allSearchRecord.get(position).getContent());
            ToSearchMusic(allSearchRecord.get(position).getContent());
        });
        //删除某个条目
        as_search_flow.setOnLongClickListener((view, position) -> {
            DialogUtils.showYesOrNoTipDialog("删除单条", "确定删除这条历史记录吗?\n删除后不可撤销~", "取消", "删除", new DialogUtils.YesOrNoDismissCallBack() {
                @Override
                public void onDone(CustomDialog dialog) {
                    if (allSearchRecord.get(position) == null) {
                        DialogUtils.showErrorToast("删除失败~");
                        initHistoryList();
                        return;
                    }
                    allSearchRecord.get(position).delete();
                    initHistoryList();
                    dialog.dismiss();
                }

                @Override
                public void onCancel(CustomDialog dialog) {
                    dialog.dismiss();
                }
            });
        });
    }

    @Override
    public void onClick(View view) {
        if (view == as_back) {
            finish();
        } else if (view == as_to_search) {
            String content = as_content.getText().toString().trim();
            if (ObjectUtils.isEmpty(content)) {
                DialogUtils.showErrorToast("搜索内容不得为空~");
            } else {
                ToSearchMusic(content);
            }
        } else if (view == as_delete_history) {
            deleteAllHistory();
        }
    }

    /**
     * 通过API发起搜索音乐
     *
     * @param content
     */
    private void ToSearchMusic(String content) {
        // 重置当前页
        pageNum = 1;
        // 处理是否保存搜索记录
        if (SugarUtils.getRecordByContent(content) == null) {
            SearchRecord searchRecord = new SearchRecord();
            searchRecord.setContent(content);
            searchRecord.setCreateTime(TimeUtils.getNowString());
            searchRecord.save();
        }
        // 发起搜索
        searchMusicPage(content, String.valueOf(pageNum), "20", new OnSearchMusicListener() {
            @Override
            public void onGetMusicSuccess(List<MusicSearchData> result) {
                // 页码更新
                pageNum++;
                as_nested_history.setVisibility(View.GONE);
                as_smart.setVisibility(View.VISIBLE);
                searchResultAdapter.setSearchContent(content);
                searchResultAdapter.setData(result);
            }

            @Override
            public void onGetMusicFail(String msg) {
                as_nested_history.setVisibility(View.VISIBLE);
                as_smart.setVisibility(View.GONE);
                DialogUtils.showErrorToast(msg);
            }
        });
    }

    /**
     * 删除所有的历史记录
     */
    private void deleteAllHistory() {
        DialogUtils.showYesOrNoTipDialog("删除全部", "确定删除所有历史记录吗?\n删除后不可撤销~", "取消", "删除", new DialogUtils.YesOrNoDismissCallBack() {
            @Override
            public void onDone(CustomDialog dialog) {
                SugarRecord.deleteAll(SearchRecord.class);
                initHistoryList();
                dialog.dismiss();
            }

            @Override
            public void onCancel(CustomDialog dialog) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (mPlayFragment != null && isPlayFragmentShow) {
            hidePlayingFragment();
            return;
        }
        super.onBackPressed();
    }

    private void hidePlayingFragment() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(0, R.anim.fragment_slide_down);
        ft.hide(mPlayFragment);
        ft.commitAllowingStateLoss();
        isPlayFragmentShow = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegister();
    }
}